package sz.com.battleship.game.GameElement;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;
import java.util.Vector;

public class AiPlayer extends Player {
	
	/**
	 * 
	 */
	private Vector<Integer> alreadyShot;
	private static final long serialVersionUID = -4485407099508644106L;
	public AiPlayer() {
		super();
		alreadyShot = new Vector<Integer>();
		gameBoard = new GameBoard();
		autoPlaceShips();
	}
	public int getShot(){
		Random randomGenerator = new Random(System.nanoTime());
		int shot = randomGenerator.nextInt(GameBoard.BOARD_SIZE);
		while(alreadyShot.contains(shot)){
			shot = randomGenerator.nextInt(GameBoard.BOARD_SIZE);
		}
		alreadyShot.add(shot);
		return shot;
	}
	private void autoPlaceShips()
	{
		Random randomGenerator = new Random(System.nanoTime());
		for(int type = 0; type <= 4;type++)
		{
			boolean placed = false; //ship has not been placed yet
			while(!placed)
			{
				if (!gameBoard.shipCanBeAdded(type))
				{ //All ships of current type have been added successfully
					placed = true;
				}
				else
				{
					int newPosition = randomGenerator.nextInt(GameBoard.BOARD_SIZE);
					ArrayList<Integer> shuffleList = new ArrayList<Integer>(); //shuffle list used to randomly determine the orientation attempts when placing ship
					
					//adding all possible orientation
					if (newPosition + (Ship.getSize(type) - 1) < 100) {shuffleList.add(newPosition + (Ship.getSize(type) - 1));}
					if (newPosition - (Ship.getSize(type) - 1) >= 0) {shuffleList.add(newPosition - (Ship.getSize(type) - 1));}
					if (newPosition + (10 * (Ship.getSize(type) - 1)) < 100) {shuffleList.add(newPosition + (10 * (Ship.getSize(type) - 1)));}
					if (newPosition - (10 * (Ship.getSize(type) - 1)) >= 0) {shuffleList.add(newPosition - (10 * (Ship.getSize(type) - 1)));}
					
					//Shuffling them
					Collections.shuffle(shuffleList, randomGenerator);
					
					for(int newPosition2 : shuffleList)
					{
						if (gameBoard.placeShip(newPosition, newPosition2, type));
						{
							break;
						}
					}
				}
			}
		}
	}
}
